import echarts from "echarts";
const echartsConfig = {
    /**
   * 组装echarts数据格式
   * @param {*} resource 
   * @param {*} params 
   * @param {*} sortParams 排序规则
   */
  arrayToECharts(resource, params, sortParams) {
    let result = {
      seriesData: [],
      xAxisData: []
    }
    let seriesData = [];
    let xAxisData = [];
    try {
      const { seriesItems, ...others } = params
      let { xField, ...other } = others;
      if (seriesItems && resource && Array.isArray(resource) && Array.isArray(seriesItems)) {
        if (sortParams) {
          // asc 按升/ desc 降序
          const { sortField, orderBy } = sortParams
          switch (orderBy) {
            case 'asc':
              resource.sort((a, b) => a[sortField] - b[sortField])
              break;
            case 'desc':
              resource.sort((a, b) => b[sortField] - a[sortField])
              break;
          }
        }
        seriesItems.forEach((element, index) => {
          const { field, name, ...items } = element;
          let data = []
          resource.forEach(ele => {
            data.push(ele[field])
          });
          seriesData[index] = items;
          Object.assign(seriesData[index], { data: data, name })
        })
        xField = xField ? xField : 'time'
        resource.forEach(ele => {
          xAxisData.push(ele[xField])
        })
        Object.assign(result, { xAxisData: xAxisData }, { seriesData: seriesData })
      }
      if (other) {
        Object.assign(result, other)
      }
    } catch (e) {
      console.error(e.message)
    }
    return result;
  },
  formatPieData(resource, params){
    let result = {
        seriesData: []
      }
      const { field, ...other } = params;
  
      let seriesData = []
      if (resource && Array.isArray(resource) && field && Array.isArray(field)) {
        field.forEach(element => {
          let data = [];
          const { value, name } = element;
          resource.forEach(ele => {
            data.push({ value: ele[value], name: ele[name] })
          })
          seriesData.push({ data: data })
        })
        Object.assign(result, { seriesData: seriesData })
      }
      return result;
  },
  PipColor: ['#4482ff', '#fbd437', '#4ecb73', '#975fe5', '#f04864', '#00CEDB', '#00F0C6', '#2ED739', '#A4E32A', '#E5E734', '#F6C942', '#E99932', '#E97C33', '#EC5750', '#B73434'],
  /**
   * 饼状图
   * @param {*} seriesData , 如：[{ name: 'af', data: [{name: "自报", value: 6}, {name: "巡检", value: 3}, {name: "查漏", value: 0}, {name: "热线", value: 0}] }]
   * @param {*} color 
   * @param {*} other
   */
  PieECharts(params, color = this.PipColor, otherParams) {
    let option = {
        color: color,
        series: []
    }
    const { seriesData = [] } = params;
    const { ...other } = otherParams
    let series = [];
    if (Array.isArray(seriesData)) {
       seriesData.forEach((ele, i) => {
        const { name, data } = ele;
        series[i] = this.PipStyle(other)
        Object.assign(series[i], { name: name ? name : '', data: data.sort(function (a, b) { return b.value - a.value }) })
      })
    }
    option.series = series;
    return option;
  },
  PipStyle(params) {
    const self = this;
    const radius = params && params.radius ? params.radius : ['50%', '70%']
    const formatType = params && params.formatType ? params.formatType : 'default'
    const unit = params && params.unit ? params.unit : ''
    let result = {
      type: 'pie',
      center: ['50%', '60%'],
      radius,
      data: [],
      label: {
        normal: {
          textStyle: { fontSize: 11 },
          formatter: function(param) {
            return self.formatPieLabel(param, formatType, unit)
          }
        }
      },
    }
    return result;
  },
  formatPieLabel(params, type, unit = '') {
    const { name, value, percent } = params;
    let result = `${name}`;
    switch (type) {
      case 'onlyPercent':
        result = `${name}\n${percent}%`;
        break;
      case 'percent':
        result = `${name}: ${value}\n(${percent}%)`;
        break;
      case 'value':
        result = `${name}\n${value}${unit}`;
        break;
    }
    return result;
  },
  BarECharts(params = {}, color = ['#188fff']) {
    const { seriesData, xAxisData, yAxis } = params;
    let option = {
      color,
      tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器，坐标轴触发有效
          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        }
      },
      grid: { left: '2%', right: '4%', bottom: '2%', top: '15%', containLabel: true },
      xAxis: [{
        type: 'category',
        data: xAxisData ? xAxisData : [],
        axisLine: { lineStyle: { color: '#333' }},
        axisTick: { alignWithLabel: true },
        axisLabel: {
          // interval: 0,
          color: '#333', textStyle: { fontFamily: 'Microsoft YaHei' }},
      }],
      yAxis: {
        name: yAxis && yAxis.name ? yAxis.name : '',
        type: 'value',
        axisLine: { show: true, lineStyle: { color: '#333' }},
        splitLine: { show: true, lineStyle: { type: 'dashed' }},
        axisTick: { show: true },
        axisLabel: {},
      },
      series: []
    };

    let series = []
    if (seriesData && Array.isArray(seriesData)) {
      seriesData.forEach((ele, i) => {
        series[i] = this.defaultBar(color[i]);
        Object.assign(series[i], {
          name: ele.name ? ele.name : '',
          data: ele.data,
          barWidth: '30%',
        })
      })
    }
    option.series = series;
    return option;
  },
  defaultBar(color) {
    let result = {
      type: 'bar',
      // itemStyle: {
      //   normal: { color },
      // },
      data: []
    };
    return result;
  },
  // 折线图
  LineECharts(params, color= ['#4482ff']){
    const { seriesData, xAxisData, yAxis } = params;
    let option = { 
      color,
      grid: { left: '2%', right: '4%', bottom: '2%', top: '15%', containLabel: true },
      xAxis: {
          type: 'category',
          data: xAxisData ? xAxisData : [],
      },
      yAxis: {
          name: yAxis && yAxis.name ? yAxis.name : '',
          splitLine: {lineStyle:{type:'dashed'}},//设置线的样式
      },
      series: []
  };

  let series = []
    if (seriesData && Array.isArray(seriesData)) {
      seriesData.forEach((ele, i) => {
        series[i] = this.defaultLine();
        Object.assign(series[i], {
          name: ele.name ? ele.name : '',
          data: ele.data
        })
      })
    }
    option.series = series;
  return option;
  },
  defaultLine(color) {
    let result = {
      type: 'line',
      smooth: true,
      symbol: 'circle',//点的样式
      symbolSize: 0,//点的大小
      areaStyle: {},
    };
    return result;
  },
  /**
   * 饼状图
   * @param {*} params 
   * @param {*} color 
   */
  pipECharts(params = {}, color = this.PipColor) {
    const { seriesData } = params;

    let option = {
      color: color,
      grid: {
        top: 0,
        letf: 0,
        right: 0,
        bottom: 0,
        containLabel: true
      },
      tooltip: {
        trigger: 'item',
        formatter:function (parms){
            return `${parms.marker} ${parms.name}</br>数量：${parms.data.value}</br>占比：${parms.percent}%`;
        }
      },
      series: []
    };
    let series = [];
    if (seriesData) {
      seriesData.forEach((ele, i) => {
        const { name, data } = ele;
        series[i] = this.defaultPipStyle(color[i])
        Object.assign(series[i], { name: name ? name : '', data: data.sort(function (a, b) { return b.value - a.value }) })
      })
    }
    option.series = series;
    return option;
  },
  defaultPipStyle(color) {
    let result = {
      type: 'pie',
      center: ['50%', '50%'],
      radius: ['50%', '70%'],
      data: [],
      label: {
        normal: {
            textStyle: {
                fontSize: 12
            },
            formatter: function(param) {
                return param.name + '(' + param.percent + '%)';
            }
        }
    },
    }
    return result;
  },
  barEChartsOption(params = {}, color = [['#FF6E02', '#FFFF00'], ['#F1487A', '#FFDC44'], ['#248ff7', '#6851f1']]) {
    const { showDataZoom, seriesData, xAxisData } = params;
    let option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器，坐标轴触发有效
          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        }
      },
      grid: {
        left: '2%',
        right: '4%',
        bottom: '10%',
        top: '5%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xAxisData ? xAxisData : [],
        axisLine: {
          lineStyle: {
            color: '#19668C'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#fff',
          textStyle: {
            fontFamily: 'Microsoft YaHei'
          }
        },
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false,
          lineStyle: {
            color: 'white'
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: 'rgba(255,255,255,0.2)'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {}
      },
      series: []
    };

    // TODO: 其它参数
    if (showDataZoom) {
      Object.assign(option, { dataZoom: this.initDataZoom() })
    }
    let series = []
    if (seriesData && Array.isArray(seriesData)) {
      seriesData.forEach((ele, i) => {
        series[i] = this.defaultBarStyle(color[i]);
        Object.assign(series[i], {
          name: ele.name ? ele.name : '',
          data: ele.data
        })
      })
    }
    option.series = series;
    return option;
  },
  defaultBarStyle(color) {
    let result = {
      type: 'bar',
      barWidth: '15%',
      itemStyle: {
        normal: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            offset: 0,
            color: color[0]
          }, {
            offset: 1,
            color: color[1]
          }]),
          barBorderRadius: 12,
        },
      },
      data: []
    };
    return result;
  },
  initDataZoom() {
    let result = [{
      show: true,
      height: 10,
      xAxisIndex: [0],
      bottom: '2%',
      start: 20,
      end: 80,
      handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
      handleSize: '100%',
      handleStyle: {
        color: "#BFBFBF",
      },
      textStyle: {
        color: "#fff"
      },
      borderColor: "#204A82"
    }, {
      type: "inside",
      show: true,
      height: 8,
      start: 1,
      end: 35
    }]
    return result;
  },
  BarHorizontalECharts(params = {}, color = ['#4482ff']) {
    const { xAxisData, seriesData, ...others } = params;
    let option = {
      tooltip: {
        show: true,
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器，坐标轴触发有效
          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        }
      },
      color,
      grid: {
        top: '10',
        bottom: '0',
        left: '10',
        containLabel: true
      },
      xAxis: [{
        // show: false
        axisLabel: {
          interval: 0
        },
        splitLine: {
          lineStyle: {
              type: 'dashed'
          }
        },
      }],
      yAxis: {
        type: 'category',
        data: xAxisData ? xAxisData : [],
      },
      series: []
    };

    let series = []
    if (seriesData && Array.isArray(seriesData)) {
      seriesData.forEach((ele, i) => {
        const { name, data, ...other } = ele;
        series[i] = this.horizontalBarStyle(color[i], other);
        Object.assign(series[i], {
          name: name ? name : '',
          data: data
        })
      })
    }
    option.series = series;

    return option
  },
  horizontalBarStyle(color, other) {
    let result = {
      type: 'bar',
      barWidth: '50%',
      // barCategoryGap: '20',
      // itemStyle: {
      //   normal: {
      //     barBorderRadius: [10, 10, 10, 10],
      //     color: new echarts.graphic.LinearGradient(0, 0, 1, 0,[
      //       { offset: 0, color: color[0] },
      //       { offset: 1, color: color[1] }]
      //     ),
      //     label: { show: true, position: 'right', textStyle: { color: '#fff', fontSize: '12' } }
      //   }
      // },
      label: {
        normal: {
            show: true,
            position: 'right',
            textStyle: {
                color: '#4482ff',
                fontSize: '12',
            }
        }
      },
      data: []
    }
    if(other){
      Object.assign(result, other)
    }
    return result;
  },
  /**
   * 多功能图表
   */
  commonEChartsOptions(params , color = ['68, 130, 255', '78, 203, 115', '251, 212, 55'], other) {
    // params = {
    //   xAxisData: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    //   yAxis: [{ name: '个' }, { name: '%' }],
    //   seriesData: [
    //     { type: 'bar', style: 'areaStyle', name: '新增贷款', data: [100, 200, 300, 400, 500, 350, 610, 220] },
    //     { type: 'line', name: '环比', yAxisIndex: 1, data: [10, 12, 15, 20, 24, 10, 12, 15] },
    //     { type: 'line', name: '同比', yAxisIndex: 1, data: [8, 18, 10, 23, 20, 15, 10, 7] }
    //   ]
    // }
    let option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        top: '20%',
        // letf: 0,
        // right: 0,
        bottom: 0,
        containLabel: true
      },
      xAxis: [{
        show: true,
        type: 'category',
        scale: true,
        axisTick: {
          alignWithLabel: true, // 刻度线和标签对齐,也可以为false
        },
        data: params && params.xAxisData ? params.xAxisData : []
      }],
      yAxis: [],
      series: []
    };

    // 处理legend
    if(other && other.showLegend){
      const legend = {
        data: params && params.seriesData && params.seriesData instanceof Array ? params.seriesData.map(function (item) {
          return item.name
        }) : [],
        itemWidth: 12,
        itemHeight: 10,
        textStyle: {
          fontSize: 11,
        }
      }
      Object.assign(option, { legend })
    }
    
    // 处理 yAxis,双坐标;yAxisIndex:1
    let yAxisData = []
    if (params && params.yAxis && Array.isArray(params.yAxis)) {
      const { yAxis } = params;
      yAxis.forEach((element, i) => {
        yAxisData.push(this.inityAxisStyle(element)) // 初始化并合并
      })
    } else {
      yAxisData = this.inityAxisStyle()
    }
    option.yAxis = yAxisData;
    // 处理 series值
    if (params && params.seriesData) {
      let optionSeries = params.seriesData;
      let seriesData = [];
      for (let i = 0; i < optionSeries.length; i++) {
        let items = optionSeries[i];
        let { style } = items;
        // 功能：初始化默认样式
        seriesData[i] = this.initSeriesStyle(color[i], items);
        // 功能：处理数据
        Object.assign(seriesData[i], {
          name: items.name ? items.name : '',
          data: items.data,
          type: items.type,
          barWidth: items.barWidth ? items.barWidth :'35%',
        })
        // 功能：设置style类型，用于处理如渐变等
        switch (style) {
          case 'areaStyle':
            Object.assign(seriesData[i], { areaStyle: this.areaStyle(color[i]) })
            break;
        }
      }
      option.series = seriesData;
    }

    return option;
  },
  inityAxisStyle(params) {
    let result = {
      type: 'value',
      // scale: true,
      axisLabel: {
        formatter: '{value}'
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      }
    }
    Object.assign(result, params)
    return result;
  },
  initSeriesStyle(color, params) {
    let result = {
      smooth: false,
      showSymbol: true,
      symbol: 'circle',
      lineStyle: {
        normal: {
          color: 'rgba(' + color + ',1)',
        }
      },
      itemStyle: {
        normal: {
          color: 'rgba(' + color + ',1)',
          shadowColor: 'rgba(' + color + ',1)',
        }
      }
    }
    Object.assign(result, params)
    return result;
  },
  areaStyle(color) {
    return {
      normal: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
          offset: 0,
          color: 'rgba(' + color + ',.5)'
        }, {
          offset: 1,
          color: 'rgba(' + color + ',.1)'
        }], false)
      }
    }
  }
}

export default echartsConfig;